import datetime
import json
from os import path
from time import sleep, strftime, localtime
from urllib import request, parse

from .dao import Dao
from .utils import sub_time


def exec_warn(url):
    with request.urlopen(url) as f:
        if int(f.status) == 200:
            res = f.read().decode('UTF-8')
            query = json.loads(res)
            if int(query['code']) == 200:
                return True
    return False


def check_downtime(dao):
    now = datetime.datetime.now()
    if check_end(dao):
        res = dao.query('SELECT MAX(createTime)createTime FROM HTML_PARAM')
        create_time = res[0]['createTime']
        max_time = datetime.datetime.fromtimestamp(create_time)
        seconds = (now - max_time).total_seconds()
        if seconds > 600 and seconds < 18000:
            print('-----------系统宕机-----------')
            return True
    return False


def check_end(dao):
    hour_ago = sub_time(60 * 10)
    is_end = dao.query('SELECT 1 FROM HTML_PARAM WHERE stopT>0 AND createTime>?', [hour_ago])
    if is_end:
        print('-----------烧制已结束-----------')
        return False
    return True


def check_runaway(dao):
    hour_ago = sub_time(10)
    if dao.query('SELECT 1 FROM HTML_PARAM WHERE tem1-maxt>5 AND createTime>?', [hour_ago]):
        print('--------------温控失灵------------')
        return True
    return False


def check_max_run_time(dao):
    hour_ago = sub_time(60 * 3)
    if dao.query('SELECT 1 FROM HTML_PARAM WHERE m>3600*5 AND createTime>?', [hour_ago]):
        print('--------------升温缓慢------------')
        return True
    return False


def analysis(cf):
    dao = Dao(cf['db'])
    i = 0
    while 1:
        sleep(cf['interval'])
        if path.exists(cf['error_file']):
            i += 1
            err = None
            try:
                # 1系统宕机
                if cf['check_downtime'] and check_downtime(dao):
                    err = '系统失联'
                # 2温控失灵
                if not err and cf['check_runaway'] and check_runaway(dao):
                    err = '2温控失灵'
                # 3升温缓慢
                if not err and cf['check_max_run_time'] and check_max_run_time(dao):
                    err = '3升温缓慢'

                if err:
                    urlencode = parse.urlencode({'sw': 1, 'err': err})
                    if exec_warn(cf['warn_url'] + '?' + urlencode):
                        print('启动报警成功')
                    else:
                        print('启动报警失败')
                else:
                    print('[%s][analysis_task][NO-%d]->检查系统运行正常' % (strftime("%Y-%m-%d %H:%M:%S", localtime()), i))
            except Exception as error:
                print('analysis error->', error)
